﻿namespace Dz.WorkerService
{
    public class TaskScheduler : IAsyncDisposable
    {
        
        private readonly List<BaseTaskItem> _tasks = new();

        public TaskScheduler()
        {
        }

        public void AddTask(BaseTaskItem task)
        {
            lock (_tasks)
            {
                _tasks.Add(task);            
            }
        }


        public async ValueTask DisposeAsync()
        {
            List<BaseTaskItem> tasksToDispose;

            lock (_tasks)
            {
                tasksToDispose = _tasks.ToList();
                _tasks.Clear();
            }

            foreach (var task in tasksToDispose)
            {
                await task.DisposeAsync();
            }
            
        }
    }
}
